<?php
namespace Tongcheng\Controller;
use Think\Controller;
class ShopController extends CommonController {
    public function index(){
        // $cate = array("car"=>"汽车模板", 'jiaoyu'=>"教育模板");
        if(IS_AJAX){
            $model = M("Shop");
            $map = array();
            $map['tp_shop.wid'] = session('wid');
            //$map['is_pay'] = 1;
            $whereor['is_pay'] = 1;
            $whereor['status'] = 2;
            $whereor['_logic'] = 'or';
            $map['_complex'] = $whereor;

            $res['count'] = $model->where($map)->count();
            $page = $_GET['page']?$_GET['page']:1;
            $limit = $_GET['limit']?$_GET['limit']:10;

            $searchC = [];
            if ($_GET['sCont']) {
                //商家名称 || 联系人 || 联系电话
                $searchC['name'] =['like', '%'.$_GET['sCont'].'%'];
                $searchC['username'] =['like', '%'.$_GET['sCont'].'%'];
                $searchC['tel'] =['like', '%'.$_GET['sCont'].'%'];
                $searchC['_logic'] = 'or';
                $map['_complex'] = $searchC;
            }
            if(I('sType')){
                switch ($_GET['sType']) {
                    case 1: //置顶
                        $map['is_top'] = 1;
                        break;
                    case 2: //屏蔽
                        $map['is_shield'] = 1;
                        break;
                    case 3: //待审核
                        $map['status'] = 0;
                        break;
                    case 4: //待认领
                        $map['status'] = 2;
                        break;
                }
            }

            //$res['list'] = $model->where($map)->where($mapS)->order('last_time desc')->page("{$page},{$limit}")->select();
            $res['list'] = $model->where($map)->order('last_time desc')->page("{$page},{$limit}")->select();
            //echo $model->getLastSql();exit;

            foreach($res['list'] as $k=>$v){
                $tui = M("tui")->where(['wid'=>session('wid'),'aid'=>$v['shop_id'],"type"=>'shop'])->find();
                if(!$tui || !$tui['status']){
                    $res['list'][$k]['is_tui'] = 0;
                }else{
                    $res['list'][$k]['is_tui'] = 1;
                }
            }
            $this->ajaxReturn($res);
        }else{
            $this->display();
        }  
    }
    public function  del()
    {
        $model = M("Shop");
        $map['shop_id'] = I('id');
        $re = $model->where($map)->delete();
        if($re){
            $this->success("操作成功！");
        }else{
            $this->error("网络忙，请稍后再试！");
        }

    }
    //导入商家  excel
    public function uploadexcel()
    {
        if(IS_File){
            if (!empty ( $_FILES)) {
                // 上传文件
                $upload = new \Think\Upload();                      // 实例化上传类
                $upload->maxSize = 10485760;                 // 设置附件上传大小
                $upload->exts = array('xls', 'xlsx');       // 设置附件上传类型
                $upload->rootPath = './Uploads/';             // 设置附件上传根目录
                $upload->autoSub = false;                         // 将自动生成以photo后面加时间的形式文件夹，关闭
                $info = $upload->upload();                                   // 上传文件
                $exts = $info['file']['ext'];                                 // 获取文件后缀
                $filename = $upload->rootPath . $info['file']['savename'];        // 生成文件路径名
                if (!$info) {                                                     // 上传错误提示错误信息
                    $this->error($upload->getError());
                } else {                                                           // 上传成功
                    import("Vendor.excel.PHPExcel");                             // 导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
                    //$PHPExcel = new \PHPExcel();                                 // 创建PHPExcel对象，注意，不能少了\
                    if ($exts == 'xls') {                                        // 如果excel文件后缀名为.xls，导入这个类
                        import("Vendor.excel.PHPExcel.Reader.Excel5");
                        $PHPReader = new \PHPExcel_Reader_Excel5();
                    } else
                        if ($exts == 'xlsx') {
                            import("Vendor.excel.PHPExcel.Reader.Excel2007");
                            $PHPReader = new \PHPExcel_Reader_Excel2007();
                        }
                    $PHPExcel = $PHPReader->load($filename);                     // 载入文件
                    $currentSheet = $PHPExcel->getSheet(0);                      // 获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
                    $allColumn = $currentSheet->getHighestColumn();              // 获取总列数
                    $allRow = $currentSheet->getHighestRow();                    // 获取总行数
                    for ($currentRow = 0; $currentRow <= $allRow; $currentRow++) {// 循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
                        for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {// 从哪列开始，A表示第一列
                            $address = $currentColumn . $currentRow;             // 数据坐标
                            $ExlData[$currentRow][$currentColumn] = $currentSheet->getCell($address)->getValue();// 读取到的数据，保存到数组$ExlData中
                        }
                    }
                    unset($ExlData[0]);//清楚数组0的空值,这一组没有数据
                    ///unset($ExlData[1]);//excel表头，第一行
                    ini_set('max_execution_time', '500');//设置导入最大时长。
                    $arr = array_values($ExlData);//重新排序数组键名
                    foreach($arr as $k=>$v){
                        if($v["A"] != null){//不导入空值
                            //处理时间格式错误
                            import("Vendor.excel.PHPExcel.Shared.Date");
                            $shared = new \PHPExcel_Shared_Date();
                            /*if(trim($v["J"])=="通过"){$zt = 2;}else{$zt = 1;}
                            if(trim($v["L"])=="流标"){$zb = 0;}else{$zb = 1;}
                            if($v["D"] !=null){$d = date("Y-m-d",$shared ->ExcelToPHP($v["D"]));}else{$d=null;}*/
                            $data['name'] = $v["B"];//店铺名称
                            $data['address'] =$v["C"];//店铺地址
                            $data['tel'] =$v["D"];//电话
                            //$data['county_name'] = $v["G"];//市或者县区名字
                           // $data['site_name'] = "全辖区";//
                            if($v['k'] != null){
                                $data['pics'] = $v["K"];//图片
                            }else{
                                $data['pics'] = 'https://www.58zltc.com/images/nopics.png';
                            }
                            $data['wid'] = session('wid');
                            $data['create_time'] = date("Y-m-d H:i:s",time());
                            $data['join_end_time'] = date("Y-m-d H:i:s",strtotime("+6 month",time()));
                            $data['status'] = 2;
                            $data['type'] = 'base';
                            //dump($data);exit();
                            $re = M("shop")->add($data);
                            if($re){
                                unset($data);
                            }else{
                                die("<script>alert('导入出错，请重试！');history.back(-1);</script>");
                            }
                        }else{
                            die("<script>alert('导入数据不能为空！');history.back(-1);</script>");
                        }
                    }
                }
            }

        }
        $this->display("Shop/index");

    }
   /* public function uploadexcel(){
        if($_FILES['file']){
            //上传到七牛
            $setting=C('UPLOAD_FILE_QINIU');
            $Upload = new \Think\Upload($setting);
            $info = $Upload->upload($_FILES);
            $file = $info['file'];
            if($file['url'] ){
                if($file['ext'] == 'xls' || $file['ext'] == 'xlsx'){
                     $this->excel(substr($file['url'],15),$file['ext']);
                }else{
                    //上传文件格式错误
                    $this->success("上传文件格式错误!",U('Shop/index'));
                }
            }else{
                return false;
            }
            //$this->redirect("Shop/index");
        }
    }*/
    public function tui(){
        $r = tui("shop",I('id'),session('wid'),$_POST['status']);
        if($r){
            $this->success("操作成功！");
        }else{
            $this->error("网络忙，请稍后再试！");
        }
    }

    //申请生成小程序
    public function createmini()
    {
        $eq['shop_id'] = I('shop_id');
        $shop = M("shop")->where($eq)->find();
        if($shop['has_mini']){
            $data['code'] = 1;
            $data['msg'] = "小程序已生成，无需再次生成";
            $this->ajaxReturn($data);
            exit;
        }
        $new['type'] = I("type");
        $new['has_mini']  = 1;
        $r = M("Shop")->where($eq)->save($new);
        if($r){
            $data['code'] = 0;
            $data['msg'] = "申请成功，请等待审核";
            $this->ajaxReturn($data);
        }else{
            $data['code'] = 1;
            $data['msg'] = "网络繁忙，请稍后再试~";
            $this->ajaxReturn($data);
        }
    }
    //生成小程序
    public function mini()
    {
        $appid = C("OPEN_APPID");
        $eq['wid'] = session('wid');
        $eq['shop_id'] = $_GET['id'];
        if(IS_AJAX){
            if(I('session')){
                S("mini_shopid",null);
                exit;
            }
            //$r = M("Shop")->where($eq)->find();
            $sid = S("mini_shopid");
            if($sid && $sid != $eq['shop_id']){
                $data=array(
                    "msg" => "当前请求过多，请稍后再试！",
                    "code"=>3
                );
                $this->ajaxReturn($data);
            }
            //if($r>=0){
            //判断是否已经授权
            $mini = M('wechat')->where(array("shop_id"=>$eq['shop_id']))->find();
            if($mini){
                $data=array(
                    "url" => U("Index/fabu",array("shop_id"=>$eq['shop_id'])),
                    "code"=>1
                );
            }else{
                //锁住机制session判断
                S("mini_shopid",$eq['shop_id'],120);
                $pre_auth_code = $this->get_pre_auth_code();
                $redirect_uri = urlencode("https://www.58zltc.com");
                $url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid={$appid}&pre_auth_code={$pre_auth_code}&redirect_uri={$redirect_uri}";
                $data=array(
                    "url" => $url,
                    "code"=>2
                );
            }

            $this->ajaxReturn($data);
            //}
            /*else{
                $this->error("网络忙，请稍后再试！".M("Shop")->getLastSql());
            }*/
        }else {
            $info = M("Shop")->where($eq)->find();
            $types = array(
                array('title' => '通用模板', 'value' => ' '),
                array('title' => '汽车模板', 'value' => 'car'),
                array('title' => '教育模板', 'value' => 'jiaoyu'),
                array('title' => '建材模板', 'value' => 'jiancai')
            );
            $this->assign('info', $info);
            $this->assign('types', $types);
            $this->display();
        }
    }

    public function get_pre_auth_code(){
        $code = S("pre_auth_code{$_SESSION['uid']}");
        if($code){
            return $code;
        }
        $token = $this->get_component_access_token();
        if(!$token){
            return "";
        }

        $url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token={$token}";
        $post_data = array(
            "component_appid"=>C("OPEN_APPID"));
        $json = json_encode($post_data);
        $res = $this->ihttp_post($url, $json);
        $td = json_decode($res, true);
        if($td['pre_auth_code']){
            S("pre_auth_code", $td['pre_auth_code'], $td['expires_in'] - 60);
            return $td['pre_auth_code'];
        }else{
            return "";
        }
    }

    private function get_component_access_token(){
        $token = S("component_access_token");
        if($token){
            return $token;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";

        $post_data = array(
            "component_appid"=>C("OPEN_APPID"),
            "component_appsecret"=>C("OPEN_APPSECRET"),
            "component_verify_ticket"=>S("component_verify_ticket"));
        $json = json_encode($post_data);
        $res = $this->ihttp_post($url, $json);
        $td = json_decode($res, true);
        if($td['component_access_token']){
            S("component_access_token", $td['component_access_token'], $td['expires_in'] - 120);
            return $td['component_access_token'];
        }else{
            return false;
        }
    }
    //pingbi
    public  function shield(){
        $data['is_shield'] = I('status');
        $a =M('shop')->where(['shop_id'=>I('id')])->save($data);
        if($a){
            $this->success("修改成功！");
        }else{
            $this->error("网络忙，请稍后再试！");
        }
    }
    public  function top(){
        $data['is_top'] = I('status');
        $a =M('shop')->where(['shop_id'=>I('id')])->save($data);
        if($a){
            $this->success("修改成功！");
        }else{
            $this->error("网络忙，请稍后再试！");
        }
    }

    public  function edit(){
        $a =M('shop')->where(['shop_id'=>I('id')])->find();
        $cate_map['wid'] = session('wid');
        $cate_map['type'] = 'shop';
        $cate_map['pid'] = 0;

        $cates = M("Cate")->where($cate_map)->field("id as cid,title")->select();
        // dump($cates);
        foreach ($cates as $k => $v) {
            $cate_map['pid'] = $v['cid'];
            $cates[$k]['cid'] = $v['cid'];
            $cates[$k]['title'] =  $v['title'];
            $sub_cates = M("Cate")->where($cate_map)->field("id as cid,title")->select();
            if($sub_cates){
                $cates[$k]['sub_cates'] = $sub_cates;
            }else{
                $cates[$k]['sub_cates'][] = array('cid'=>0, 'title'=>'全部');
            }
        }

        $map['wid'] = session('wid');
        $wechat = M("Wechat")->where($map)->find();
        $where['city_code'] = $wechat['city'];
        $city = M("City")->where($where)->find();
        $where1['pid'] = $city['id'];
        $site_arr2 = M("City")->where($where1)->getField("city_name",true);
        if($wechat['city'] == 0){

            $site_arr['name'] = '全国';
            $site_arr['sub_site'] = array('全国');
        }else{
            $site_arr['name'] = $city["city_name"];
            if(!$site_arr2){
                $site_arr['sub_site'] = array("全辖区");
            }else{
                $site_arr['sub_site'] = $site_arr2;
            }
        }
        $citys[] = $site_arr;
        $this->assign('cates',$cates);
        $this->assign('citys',$citys);
        $this->assign('vo',$a);
        $this->display('add');
    }
    public function add(){
        if(IS_POST){
            if(I('id')){
                unset($_POST['file']);
                foreach ($_POST as $key => $value) {
                    if(empty($value)){
                        $this->error('请填写全部信息！');
                    }
                }
                $cate = M('cate')->where(['id'=>$_POST['cid']])->find();
                if($cate['pid']){
                    $pcate = M('cate')->where(['id'=>$cate['pid']])->find();
                }
                $_POST['wid'] = session('wid');
//                $_POST['is_pay'] = 1;
//                $_POST['status'] = 2;
                $_POST['cate'] = $pcate['title']; //分类
                $_POST['sub_cate'] = $cate['title']; //分类
                //地区
                $map['wid'] = session('wid');
                $wechat = M("Wechat")->where($map)->find();
                $where['city_code'] = $wechat['city'];
                $city = M("City")->where($where)->find();
                $_POST['county_name'] = $city['city_name'];
                $_POST['site_name'] = $_POST['city'];
                $_POST['create_time'] = date('Y-m-d H:i:s',time());

                if(M("Shop")->where(['shop_id'=>I('id')])->save($_POST)){
                    $this->success("修改成功！");
                }else{
                    $this->error("网络忙，请稍后再试！".M()->getLastSql());
                }
            }else{
                unset($_POST['file']);
                unset($_POST['id']);
                foreach ($_POST as $key => $value) {
                    if(empty($value)){
                        $this->error('请填写全部信息！');
                    }
                }
                $cate = M('cate')->where(['id'=>$_POST['cid']])->find();
                if($cate['pid']){
                    $pcate = M('cate')->where(['id'=>$cate['pid']])->find();
                }
                $_POST['wid'] = session('wid');
                $_POST['is_pay'] = 0;
                $_POST['status'] = 2;
                $_POST['cate'] = $pcate['title']; //分类
                $_POST['sub_cate'] = $cate['title']; //分类
                //地区
                $map['wid'] = session('wid');
                $wechat = M("Wechat")->where($map)->find();
                $where['city_code'] = $wechat['city'];
                $city = M("City")->where($where)->find();
                $_POST['county_name'] = $city['city_name'];
                $_POST['site_name'] = $_POST['city'];
                $_POST['create_time'] = date('Y-m-d H:i:s',time());
                $_POST['type'] = 'base';
                if(M("Shop")->add($_POST)){
                    $this->success("添加成功！");
                }else{
                    $this->error("网络忙，请稍后再试！".M()->getLastSql());
                }
            }

        }else{
            $cate_map['wid'] = session('wid');
            $cate_map['type'] = 'shop';
            $cate_map['pid'] = 0;

            $cates = M("Cate")->where($cate_map)->field("id as cid,title")->select();
            // dump($cates);
            foreach ($cates as $k => $v) {
                $cate_map['pid'] = $v['cid'];
                $cates[$k]['cid'] = $v['cid'];
                $cates[$k]['title'] =  $v['title'];
                $sub_cates = M("Cate")->where($cate_map)->field("id as cid,title")->select();
                if($sub_cates){
                    $cates[$k]['sub_cates'] = $sub_cates;
                }else{
                    $cates[$k]['sub_cates'][] = array('cid'=>0, 'title'=>'全部');
                }
            }
            $this->assign('cates',$cates);

            $map['wid'] = session('wid');
            $wechat = M("Wechat")->where($map)->find();
            $where['city_code'] = $wechat['city'];
            $city = M("City")->where($where)->find();
            $where1['pid'] = $city['id'];
            $site_arr2 = M("City")->where($where1)->getField("city_name",true);
            if($wechat['city'] == 0){

                $site_arr['name'] = '全国';
                $site_arr['sub_site'] = array('全国');
            }else{
                $site_arr['name'] = $city["city_name"];
                if(!$site_arr2){
                    $site_arr['sub_site'] = array("全辖区");
                }else{
                    $site_arr['sub_site'] = $site_arr2;
                }
            }
            $citys[] = $site_arr;
            $this->assign('citys',$citys);

            $this->display();
        }
    }

    public function type(){
        $eq['wid'] = session('wid');
        $eq['shop_id'] = $_GET['id'];
        //查询店铺信息
        $shop = M('shop')->where(['shop_id'=>$eq['shop_id']])->find();
        if(IS_AJAX){
            $new['type'] = I("type");
            $takeout = M('takeout_store')->where(['openid'=>$shop['openid'],'wid'=>$shop['wid']])->find();
            //如果是外卖的，查一下是否takeout_store表有数据。如果没有则新增一条
            if(I('type')=='takeout'){
                if($takeout){
                    //有数据，则修改字段is_display
                    M('takeout_store')->where(['id'=>$takeout['id']])->save(['is_display'=>1]);
                }else{
                    //没数据，则新增数据
                    $data['wid'] = $shop['wid'];
                    $data['openid'] = $shop['openid'];
                    $data['name'] = $shop['name'];
                    $data['address'] = $shop['address'];
                    $data['time'] = $shop['start_time'];//营业时间
                    $data['time2'] = $shop['end_time'];
                    $data['tel'] = $shop['tel'];
                    $data['is_rest'] = 2; //是否休息(1 是  2否)
                    $data['img'] = $shop['pics'];
                    $data['logo'] = $shop['logo'];
                    $data['coordinates'] = $shop['latitude'].','.$shop['longitude'];//经纬度
                    $data['is_display'] = 1;
                    $data['logo'] = $shop['logo'];

                    M('takeout_store')->add($data);
                }
            }else{
                if($takeout) {
                    //修改其他模板的时候，把外卖店铺改为0
                    M('takeout_store')->where(['id'=>$takeout['id']])->save(['is_display' => 0]);
                }
            }

            if(M("Shop")->where($eq)->save($new)){
                $this->success("修改成功！");
            }else{
                $this->error("网络忙，请稍后再试！".M("Shop")->getLastSql());
            }
        }else{
            //模板展示
            $info = M("Shop")->where($eq)->find();
            $types = array(
                array('title'=>'基础模板', 'value'=>'base'),
                array('title'=>'通用模板', 'value'=>''),
                array('title'=>'汽车模板', 'value'=>'car'),
                array('title'=>'教育模板', 'value'=>'jiaoyu'),
                array('title'=>'建材模板', 'value'=>'jiancai'),
                array('title'=>'酒店模板', 'value'=>'hotel'),
                array('title'=>'餐饮模板', 'value'=>'takeout'),
            );
            $this->assign('info',$info);
            $this->assign('types',$types);

            $this->display();
        }
    }

    public function tong(){
        $model = M("Shop");
        $map['wid'] = session('wid');
        $map['id'] = $_POST['id'];
        $renling = M('renling')->where($map)->find();
        $new['status'] = 1;

        $new['latitude']=$renling['latitude'];
        $new['longitude']=$renling['longitude'];
        $new['username'] = $renling['username'];
        $new['tel'] = $renling['tel'];
        $new['openid'] = $renling['openid'];
        $new['is_pay'] = $renling['is_pay'];
        $new['join_end_time'] = date("Y-m-d H:i:s",$renling['join_days'] * 3600 *24 + time());
        M('renling')->where($map)->save(['status' => 1]);

        //M('renling')->where($map)->save($new);
        if(M("shop")->where(['shop_id'=>$renling['shop_id']])->save($new)){
            sendRuzhuMessage($renling['shop_id']);
            $this->success("上线成功！");
        }else{
            $this->error("网络忙，请稍后再试！".$model->getLastSql());
        }
    }

    public function renlingList(){
        if(IS_AJAX){
            $model = M("Renling");
            $map = array();
            $map['s.wid'] = session('wid');
            $map['r.status'] = 0;

            $res['count'] = $model->alias('r')->join('tp_shop s on s.shop_id = r.shop_id')->where($map)->count();
            $page = $_GET['page']?$_GET['page']:1;
            $limit = $_GET['limit']?$_GET['limit']:10;
            $res['list'] = $model->alias('r')->field('s.*,r.status,r.id,r.username,r.tel')->join('tp_shop s on s.shop_id = r.shop_id')->where($map)->page("{$page},{$limit}")->select();
            foreach ($res['list'] as $key => $value) {
                $eq['shop_id'] = $value['shop_id'];
                $res['list'][$key]['shop_name'] = M("Shop")->where($eq)->getField('name');
            }
            $this->ajaxReturn($res);
        }else{
            $this->display();
        }  
    }
    //后台审核商家
    public function audit_shop(){
        $map['wid'] = session('wid');
        $map['shop_id'] = I('shop_id');
        //更新入驻时间
        $array_shop = M('shop')->where(['shop_id' => I('shop_id')])->find();
        $join_time = $array_shop['join_fee_time'] + time();
        $suc = M('shop')->where(['shop_id' => I('shop_id')])->save(['join_end_time' => date('Y-m-d H:i:s', $join_time)]);
        if ($suc) {
            $new['status'] = 1;
            $r = M("shop")->where($map)->save($new);
            //echo M()->getLastSql();exit;
            if($r){
                sendRuzhuMessage(I('shop_id'));
                $this->success("审核成功！");
            }else{
                $this->error("网络忙，请稍后再试！");
            }
        } else {
            $this->error("网络忙，请稍后再试！");
        }

    }
    public function renling(){
        $model = M("renling");
        $map['wid'] = session('wid');
        $map['id'] = $_POST['id'];

        $new['status'] = 1;

        $info = $model->where($map)->find();
        $eq['shop_id'] = $info['shop_id'];

        $data['openid'] = $info['openid'];
        $data['tel'] = $info['tel'];
        $data['username'] = $info['username'];
        M("Shop")->where($eq)->save($data);
        if($model->where($map)->save($new)){
            $this->success("认领成功！");
        }else{
            $this->error("网络忙，请稍后再试！".$model->getLastSql());
        }
    }

    //商家入驻协议
    public function agreement () {
        $list = M('agreement')->where(['wid' => session('wid'), 'type' => 0])->order('state desc, last_time desc')->select();
        $this->assign('list', $list);
        $this->display();
    }
    //
    public function add_argeement () {
        if ($_GET['id']) {
            $find =  M('agreement')->where(['id' => $_GET['id']])->find();
            $this->assign('find', $find);
        } else {
            $find = [];
        }
        $this->assign('find', $find);
        $this->display();
    }
    //
    public function save_agreement () {
        $post = $_POST;
        $id = $post['id'];
        unset($post['id']);
        if ($id) {
            $row = M('agreement')->where(['id' => $id])->save($post);
        } else {
            $post['wid'] = session('wid');
            $post['state'] = 1;
            $post['type'] = 0;//商家入驻
            $row = M('agreement')->add($post);
        }
        if ($row) {
           $this->ajaxReturn(1);
        } else {
            $this->ajaxReturn(0);
        }
    }

    //
    public function del_agreement () {
        $id = $_POST['id'];
        $row = M('agreement')->where(['id' => $id])->delete();
        if ($row) {
            $this->ajaxReturn(['status' => 1, 'info' => '删除成功']);
        } else {
            $this->ajaxReturn(['status' => 0, 'info' => '网络繁忙']);
        }
    }
    public function up_agreement () {
        $id = $_POST['id'];
        $state = $_POST['state'];
        $state == 1 ? $state = 0 : $state = 1;
        $row = M('agreement')->where(['id' => $id])->save(['state' => $state]);
        if ($row) {
            $this->ajaxReturn(['status' => 1, 'info' => '修改成功']);
        } else {
            $this->ajaxReturn(['status' => 0, 'info' => '网络繁忙']);
        }
    }

    //商家发布协议
    public function agreement_f () {
        $list = M('agreement')->where(['wid' => session('wid'), 'type' => 1])->order('state desc, last_time desc')->select();
        $this->assign('list', $list);
        $this->display();
    }
    //
    public function add_argeement_f () {
        if ($_GET['id']) {
            $find =  M('agreement')->where(['id' => $_GET['id']])->find();
            $this->assign('find', $find);
        } else {
            $find = [];
        }
        $this->assign('find', $find);
        $this->display();
    }
    //
    public function save_agreement_f () {
        $post = $_POST;
        $id = $post['id'];
        unset($post['id']);
        if ($id) {
            $row = M('agreement')->where(['id' => $id])->save($post);
        } else {
            $post['wid'] = session('wid');
            $post['state'] = 1;
            $post['type'] = 1;//发布
            $row = M('agreement')->add($post);
        }
        if ($row) {
            $this->ajaxReturn(1);
        } else {
            $this->ajaxReturn(0);
        }
    }
    public function up_agreement_f () {
        $id = $_POST['id'];
        $state = $_POST['state'];
        $state == 1 ? $state = 0 : $state = 1;
        $row = M('agreement')->where(['id' => $id])->save(['state' => $state]);
        if ($row) {
            $this->ajaxReturn(['status' => 1, 'info' => '修改成功']);
        } else {
            $this->ajaxReturn(['status' => 0, 'info' => '网络繁忙']);
        }
    }

    //同城卡开通协议
    public function agreement_t () {
        $list = M('agreement')->where(['wid' => session('wid'), 'type' => 2])->order('state desc, last_time desc')->select();
        $this->assign('list', $list);
        $this->display();
    }
    //
    public function add_argeement_t () {
        if ($_GET['id']) {
            $find =  M('agreement')->where(['id' => $_GET['id']])->find();
            $this->assign('find', $find);
        } else {
            $find = [];
        }
        $this->assign('find', $find);
        $this->display();
    }
    //
    public function save_agreement_t () {
        $post = $_POST;
        $id = $post['id'];
        unset($post['id']);
        if ($id) {
            $row = M('agreement')->where(['id' => $id])->save($post);
        } else {
            $post['wid'] = session('wid');
            $post['state'] = 1;
            $post['type'] = 2;//
            $row = M('agreement')->add($post);
        }
        if ($row) {
            $this->ajaxReturn(1);
        } else {
            $this->ajaxReturn(0);
        }
    }
    public function up_agreement_t () {
        $id = $_POST['id'];
        $state = $_POST['state'];
        $state == 1 ? $state = 0 : $state = 1;
        $row = M('agreement')->where(['id' => $id])->save(['state' => $state]);
        if ($row) {
            $this->ajaxReturn(['status' => 1, 'info' => '修改成功']);
        } else {
            $this->ajaxReturn(['status' => 0, 'info' => '网络繁忙']);
        }
    }

    public function agreement_q () {
        $list = M('agreement_rights')->where(['wid' => session('wid')])->order('order_num desc')->select();
        $this->assign('list', $list);
        $this->display();
    }

    public function add_argeement_q () {
        if ($_GET['id']) {
            $find =  M('agreement_rights')->where(['id' => $_GET['id']])->find();
            $this->assign('vo', $find);
        } else {
            $find = [];
        }
        $this->assign('vo', $find);
        $this->display();
    }
    //
    public function save_argeement_q () {
        $post = $_POST;
        $id = $post['id'];
        unset($post['id']);
        unset($post['file']);
        if ($id) {
            $row = M('agreement_rights')->where(['id' => $id])->save($post);
        } else {
            $post['wid'] = session('wid');
            $post['state'] = 1;
            $row = M('agreement_rights')->add($post);
        }
        if ($row) {
            $this->ajaxReturn(['info' => '提交成功', 'status' => 1]);
        } else {
            $this->ajaxReturn(['info' => '网络繁忙', 'status' => 0]);
        }
    }
    public function up_agreement_q () {
        $id = $_POST['id'];
        $state = $_POST['state'];
        $state == 1 ? $state = 0 : $state = 1;
        $row = M('agreement_rights')->where(['id' => $id])->save(['state' => $state]);
        if ($row) {
            $this->ajaxReturn(['status' => 1, 'info' => '修改成功']);
        } else {
            $this->ajaxReturn(['status' => 0, 'info' => '网络繁忙']);
        }
    }

    public function del_agreement_q () {
        $id = $_POST['id'];
        $row = M('agreement_rights')->where(['id' => $id])->delete();
        if ($row) {
            $this->ajaxReturn(['status' => 1, 'info' => '删除成功']);
        } else {
            $this->ajaxReturn(['status' => 0, 'info' => '网络繁忙']);
        }
    }

    //商户参与同城卡协议
    public function agreement_shop () {
        $list = M('agreement')->where(['wid' => session('wid'), 'type' => 3])->order('state desc, last_time desc')->select();
        $this->assign('list', $list);
        $this->display();
    }
    //
    public function add_argeement_shop () {
        if ($_GET['id']) {
            $find =  M('agreement')->where(['id' => $_GET['id']])->find();
            $this->assign('find', $find);
        } else {
            $find = [];
        }
        $this->assign('find', $find);
        $this->display();
    }
    //
    public function save_agreement_shop () {
        $post = $_POST;
        $id = $post['id'];
        unset($post['id']);
        if ($id) {
            $row = M('agreement')->where(['id' => $id])->save($post);
        } else {
            $post['wid'] = session('wid');
            $post['state'] = 1;
            $post['type'] = 3;//
            $row = M('agreement')->add($post);
        }
        if ($row) {
            $this->ajaxReturn(1);
        } else {
            $this->ajaxReturn(0);
        }
    }
    public function up_agreement_shop () {
        $id = $_POST['id'];
        $state = $_POST['state'];
        $state == 1 ? $state = 0 : $state = 1;
        $row = M('agreement')->where(['id' => $id])->save(['state' => $state]);
        if ($row) {
            $this->ajaxReturn(['status' => 1, 'info' => '修改成功']);
        } else {
            $this->ajaxReturn(['status' => 0, 'info' => '网络繁忙']);
        }
    }

    //设置店铺抽成
    public function chou()
    {
        $eq['shop_id'] = I('id');
        $data['chou'] = I('chou');
        $re = M("shop")->where($eq)->save($data);
        if ($re) {
            $this->success('修改成功');
        } else {
            $this->error('网络繁忙');
        }
    }
}